package com.fita.admin.web.controller.authority;

import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.resolver.Preloading;
import com.fita.admin.entity.security.Login;
import com.fita.admin.service.DataService;
import com.fita.admin.web.resolver.Secure;
import com.fita.entity.principal.District;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * 分区管理
 *
 * @author cuteHU
 *
 */
@Controller
@RequestMapping("/districts")
@MenuSetting("menu-authority")
public class DistrictController {

	private Logger logger = LoggerFactory.getLogger(DistrictController.class);

	@Autowired
	@Qualifier("dataService")
	private DataService<District> districtService;

	/**
	 * 分区列表
	 * 
	 * @param login
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.GET)
	@MenuSetting("submenu-branch-management")
	public ModelAndView list(@Secure Login login, Page page) {

		ModelAndView modelAndView = new ModelAndView("authority/district/district-list");

		int totals = districtService.count(District.class);
		if (totals > 0) {

			List<District> districts = districtService.listByPage(District.class, page.with(totals));

			modelAndView.addObject("districts", districts);
			modelAndView.addObject("page", page);

		}
		return modelAndView;
	}

	/**
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
	public ModelAndView edit(@PathVariable("id") Long id) {

		ModelAndView modelAndView = new ModelAndView("authority/district/district-edit");

		District district = districtService.load(District.class, id);
		modelAndView.addObject("district", district);

		return modelAndView;
	}

	/**
	 * @param id
	 * @param district
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public @ResponseBody HttpResult onEdit(@PathVariable(name = "id") Long id, @Preloading("districtId") District district) {

		HttpResult httpResult = new HttpResult();

		try {

			districtService.update(district);

			httpResult.success().message("编辑分区成功");

		} catch (Exception e) {
			httpResult.fail("500").message("编辑分区失败");
			logger.error("#onEdit() - edit fail, exception is [{}]", e);
		}

		return httpResult;
	}
}
